#coding:utf-8
import threading
import os
import demjson
import server
import traceback
import time
from spider import spiderClass
from flask import Flask,request
import globalvar
import requests
import re
import helper
from zmap import zmapClass
from zgrab import zgrabClass
globalvar._init() #全局变量存储器初始化
app = Flask(__name__)
globalvar.set_value('status', 'STOP')
import datetime

#监控回调
#每10秒向指定地址进行监控传参
def Monitor(callbackURL):
    print(callbackURL)
    print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),"Open Monitor......")
    while True:
        try:
            print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),"Start Monitor......")
            if globalvar.get_value('status') == 'RUNING':
                data = {
                    'TASKID': globalvar.get_value('TASKID'),
                    'LOG':demjson.encode({'serverStatusInfo':server.getServerInfo(),
                    'TaskStatusInfo':globalvar.get_value('TaskStatusInfo')})
                }
                requests.post(callbackURL,data=data)
                print(callbackURL)
                print(demjson.encode(data))
            else:
                break
        except Exception as e:
            print(e)
        time.sleep(60)

@app.route('/')
def hello_world():
    return 'Hello World!'
@app.route('/status')
def status():
    return demjson.encode({
        'TASKID':globalvar.get_value('TASKID'),
        'serverStatusInfo':server.getServerInfo(),
        'TaskStatusInfo':globalvar.get_value('TaskStatusInfo')
    })
@app.route('/TaskResult')
def TaskResult():
    if os.path.exists('Found.txt') == True:
        return demjson.encode({'status':'success','data':open('Found.txt').read().split('\n')})
    else:
        return demjson.encode({'status':'failed','msg':'null'})
@app.route('/spider',methods=['POST'])
def addTask():
    taskInfo = demjson.decode(request.form['taskInfo'])
    global_status = globalvar.get_value('status')

    if global_status == 'RUNING':
        return demjson.encode({'status':'failed','msg':'bad'})
    else:
        scanner = spiderClass(taskInfo)
        #启动扫描
        threading.Thread(target=scanner.Run).start()
        #启动监控
        print("CALLBACKURL:",taskInfo['MonitorCallBackUrl'])
        threading.Thread(target=Monitor,args=(taskInfo['MonitorCallBackUrl'],)).start()
        #锁定状态
        globalvar.set_value('status', 'RUNING')
        return demjson.encode({'status': 'success'})
@app.route('/zmap',methods=['POST'])
def zmap():

    cidr = request.form['cidr']
    port = request.form['port']
    Band = request.form['Band']

    z = zmapClass(cidr,port,Band)

    threading.Thread(target=z.scanner).start()
    return demjson.encode({'status': 'success'})
@app.route('/zmapstatus')
def zmapstatus():
    try:
        f = open('/var/www/html/zmap.txt','r')
        content = f.read()
        f.close()
        l = content.split('\n')
        if len(l) > 10:
            log = l[-3].strip()
            res = re.findall(" (.*?)% ", log, re.S)
            progress = res[0]
            res = re.findall(" \((.*?) Kp\/s avg\)\;", log, re.S)
            res = res[0]
            speed = res.split('(')[1]
            res = re.findall("recv: (.*?) ", log, re.S)
            recv = res[0]
            return demjson.encode({
                'progress':progress,
                'speed':speed,
                'recv':recv
            })
        else:
            return 'error'
    except Exception as e:
        traceback.print_exc()
        print(e)
        return 'error'
@app.route('/zgrab',methods=['POST'])
def zgrab():
    '''{
        "ContainList": [],
        "ExcludeList": [],
        "IPFile": "http://220.167.103.51/testip.txt",
        "Port": "80",
        "ReqFile": "http://220.167.103.51/request.txt",
        "Thread": "1000",
        "TimeOut": "30",
        "TLS": "0"
    }'''
    config = demjson.decode(request.form['config'])
    zgrab = zgrabClass(
        Thread=config['Thread'],
        TimeOut=config['TimeOut'],
        Port=config['Port'],
        ReqFile=config['ReqFile'],
        IPFile=config['IPFile'],
        ContainList=config['ContainList'],
        ExcludeList=config['ExcludeList'],
        TLS=config['TLS']
    )
    zgrab.start()
    return demjson.encode({'status': 'success'})
@app.route('/zgrabstatus')
def zgrabstatus():
    return demjson.encode({
        'success': helper.wc('/var/success.txt'),
        'failure':helper.wc('/var/failure.txt')
    })
if __name__ == '__main__':
    app.run(host='0.0.0.0')